<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j content page-return-detail">
    <div class="return-detail">
      <div class="crumbs">
        <router-link
          to="/user-center/uc-return"
          class="item-a"
        >
          {{ $t('applyReturn.refundList') }}
        </router-link>
        <span class="arrow">></span>
        <span class="item-span">{{ $t('applyReturn.refundDetails') }}</span>
      </div>
      <div
        v-if="platInterSts && platInterSts===-1"
        class="return-step"
      >
        <div
          :class="['item', ((refundDetail.returnMoneySts <= 4 && refundDetail.returnMoneySts !== -1) || refundDetail.returnMoneySts === 5)?'active':'']"
        >
          <div class="number">
            ●
          </div>
          <div class="text">
            {{ $t('applyReturn.buyerSubmits') }}
          </div>
          <div class="time">
            {{ refundDetail.applyTime }}
          </div>
        </div>
        <div
          :class="['item', (refundDetail.returnMoneySts >= 2 && refundDetail.returnMoneySts <= 5)?'active':'']"
        >
          <div class="number">
            ●
          </div>
          <div class="text">
            {{ $t('applyReturn.sellerProcessing') }}
          </div>
          <div
            v-if="refundDetail.returnMoneySts >= 2 && refundDetail.returnMoneySts <= 5"
            class="time"
          >
            {{ refundDetail.handelTime }}
          </div>
        </div>
        <div
          v-if="refundDetail.applyType === 2"
          :class="['item', (refundDetail.returnMoneySts >= 3 && refundDetail.returnMoneySts <= 5)?'active':'']"
        >
          <div class="number">
            ●
          </div>
          <div class="text">
            {{ $t('applyReturn.buyerReturns') }}
          </div>
          <div
            v-if="refundDetail.returnMoneySts >= 3 && refundDetail.returnMoneySts <= 5"
            class="time"
          >
            {{ refundDetail.shipTime }}
          </div>
        </div>
        <div :class="['item', (refundDetail.returnMoneySts === 5)?'active':'']">
          <div class="number">
            ●
          </div>
          <div class="text">
            {{ $t('applyReturn.refundCompleted') }}
          </div>
          <div
            v-if="refundDetail.returnMoneySts === 5"
            class="time"
          >
            {{ refundDetail.refundTime }}
          </div>
        </div>
      </div>
      <!-- 平台介入提示 -->
      <div
        v-if="platInterSts===1 && platInterHandleTips"
        class="plat-inter-tips"
      >
        <el-icon
          :size="16"
          color="#409EFF"
        >
          <WarningFilled />
        </el-icon>
        <span class="txt">{{ platInterHandleTips }}</span>
      </div>
      <div :class="['return-order', $t('language') === 'en'?'en':'']">
        <table
          style="border-spacing: 0"
          class="order-box"
        >
          <tbody>
            <tr class="box-tit">
              <th>{{ $t('applyReturn.productInformation') }}</th>
              <th style="width: 130px;">
                {{ $t('applyReturn.transactionTime') }}
              </th>
              <th style="width: 127px;">
                {{ $t('applyReturn.numberOfApplications') }}
              </th>
              <th style="width: 160px;">
                {{ $t('applyReturn.refundAmount') }}
              </th>
              <th style="width: 127px;">
                {{ $t('status') }}
              </th>
              <th style="width: 127px;">
                {{ $t('operation') }}
              </th>
            </tr>
            <tr class="box-space">
              <td colspan="6" />
            </tr>
            <!-- 表格头 -->
            <tr class="box-hd">
              <td colspan="6">
                <div class="order-number">
                  {{ $t('applyReturn.orderNumber') }}：
                  <span class="num">{{ refundDetail.orderNumber }}</span>
                </div>
                <div class="return-number">
                  {{ $t('applyReturn.refundNumber') }}：
                  <span class="num">{{ refundSn }}</span>
                </div>
                <router-link
                  :to="{
                    path: '/shop-index',
                    query: {
                      sid: refundDetail.shopId
                    }
                  }"
                  class="shop"
                >
                  <span class="shop-icon" />
                  {{ refundDetail.shopName }}
                </router-link>
              </td>
            </tr>
            <tr
              v-for="(refundItem,index) in prodList"
              :key="index"
              class="box-tr"
            >
              <!-- 商品信息 -->
              <td>
                <div
                  class="goods-info"
                  :class="{'gift-goods-info': refundItem.giveawayOrderItemId}"
                  @click="toProdDetails(refundItem.prodId, refundItem.giveawayOrderItemId)"
                >
                  <div class="img">
                    <img-show :src="refundItem.pic" />
                  </div>
                  <div class="name-sku">
                    <div class="name">
                      {{ refundItem.prodName }}
                    </div>
                    <div class="sku">
                      <span
                        v-if="refundItem.giveawayOrderItemId"
                        class="gift-icon"
                      >{{ $t('prodDetail.gift') }}</span>
                      <span>{{ refundItem.skuName }} x{{ refundItem.prodCount }}</span>
                    </div>
                  </div>
                </div>
                <!-- 赠品：多件商品时展示 -->
                <div
                  v-if="refundDetail.orderItems.length > 1 && refundItem.giveawayList && refundItem.giveawayList.length"
                  class="gift-info"
                >
                  <div
                    v-for="(gitfItem, gitfIndex) in refundItem.giveawayList"
                    :key="gitfIndex"
                    class="gift-item"
                    @click="toProdDetails(gitfItem.prodId, gitfItem.giveawayOrderItemId)"
                  >
                    <span class="name">{{ '【' + $t('prodDetail.gift') + '】' + gitfItem.prodName }}</span>
                    <span class="num">{{ gitfItem.skuName }} ×{{ gitfItem.prodCount }}</span>
                  </div>
                </div>
                <!-- / 赠品 -->
              </td>
              <!-- 成交时间 -->
              <td
                v-if="index === 0"
                :rowspan="prodList.length"
              >
                <div class="deal-time">
                  {{ refundDetail.orderPayTime }}
                </div>
              </td>
              <!-- 数量 -->
              <td
                v-if="index === 0"
                :rowspan="prodList.length"
              >
                <div class="apply-number">
                  {{ refundDetail.goodsNum }}
                </div>
              </td>
              <!-- 金额 -->
              <td
                v-if="index === 0"
                :rowspan="prodList.length"
              >
                <div class="price-box">
                  <div class="all-price">
                    {{ $t('applyReturn.total') }}：
                    <i v-if="refundDetail.orderAmount">￥{{ Number(refundDetail.orderAmount).toFixed(2) }}</i>
                    <i v-if="refundDetail.orderAmount && refundDetail.refundScore">&nbsp;+&nbsp;</i>
                    <i v-if="refundDetail.refundScore">{{ refundDetail.refundScore }}{{ $t('applyReturn.points') }}</i>
                  </div>
                  <div class="return-price">
                    {{ $t('applyReturn.refunds') }}：
                    <i v-if="refundDetail.refundAmount">￥{{ Number(refundDetail.refundAmount).toFixed(2) }}</i>
                    <i v-if="refundDetail.refundAmount && refundDetail.refundScore">&nbsp;+&nbsp;</i>
                    <i v-if="refundDetail.refundScore">{{ refundDetail.refundScore }}{{ $t('applyReturn.points') }}</i>
                  </div>
                  <!--
                    修改退款金额：
                    1、仅退款(applyTyp:1)：买家申请(returnMoneySts:1)状态下可以修改
                    2、退货退款(applyTyp:2)：买家申请(returnMoneySts:1)
                                          状态下可以修改
                    3、整单退款(refundType:1)：不可修改
                    4、isUsedPlatformReduce 是否使用了平台优惠 （是 则不可修改）
                  -->
                  <div
                    v-if="refundDetail.refundType !== 1 &&
                      ((refundDetail.applyType === 1 &&
                        refundDetail.returnMoneySts === 1) ||
                        (refundDetail.applyType === 2 &&
                          (refundDetail.returnMoneySts === 1 ))) &&
                      !isUsedPlatformReduce"
                    class="action-a"
                    @click="modifyRefundAmount()"
                  >
                    {{ $t('applyReturn.modifyRefundAmount') }}
                  </div>
                </div>
              </td>
              <!-- 状态 -->
              <td
                v-if="index === 0"
                :rowspan="prodList.length"
              >
                <div
                  v-if="platInterSts && platInterSts!==-1"
                  class="status-box"
                >
                  <div class="type">
                    {{ ['',$t('applyReturn.refundsOnly'),$t('applyReturn.returnsAndRefunds')][refundDetail.applyType] }}
                  </div>
                  <div class="status">
                    {{ ['','平台介入中','平台同意退款','平台拒绝退款','','退款完成'][platInterSts] }}
                  </div>
                </div>
                <div
                  v-else
                  class="status-box"
                >
                  <div class="type">
                    {{ ['',$t('applyReturn.refundsOnly'),$t('applyReturn.returnsAndRefunds')][refundDetail.applyType] }}
                  </div>
                  <div
                    class="status"
                  >
                    {{ ['',$t('applyReturn.buyerApplication'),$t('applyReturn.sellerAcceptance'),$t('applyReturn.buyerShipping'),$t('applyReturn.sellerReceipt'),$t('applyReturn.successfulRefund'),$t('applyReturn.buyerWithdrawsApplication'),$t('applyReturn.merchantRefusal')][refundDetail.returnMoneySts] }}
                  </div>
                  <div
                    v-if="refundDetail.returnMoneySts === -1"
                    class="status"
                  >
                    {{ $t('applyReturn.refundClose') }}
                  </div>
                </div>
              </td>
              <!-- 操作 -->
              <td
                v-if="index === 0"
                :rowspan="prodList.length"
              >
                <!-- (买家申请 || 卖家接受 || 商家拒绝) || isCancel可撤销 -->
                <a
                  v-if="(refundDetail.returnMoneySts === 1 || refundDetail.returnMoneySts === 2 || refundDetail.returnMoneySts === 7) && refundDetail.isCancel"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="cancelApply"
                >{{ $t('applyReturn.applicationTips5') }}</a>
                <a
                  v-if="refundDetail.returnMoneySts === 2 && refundDetail.applyType === 2"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="writeLogisticsMsg"
                >{{ $t('applyReturn.fillLogistics') }}</a>
                <a
                  v-if="refundDetail.returnMoneySts === 3 && refundDetail.applyType === 2"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="writeLogisticsMsg"
                >{{ $t('applyReturn.modifyLogistics') }}</a>
                <a
                  v-if="canApplyPlatInter && platInterSts===-1 && (refundDetail.returnMoneySts === 7 || refundDetail.returnMoneySts === -1) && refundDetail.rejectTime"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="onApplyPlayIntervene(1)"
                >申请平台介入</a>
                <a
                  v-if="platInterSts===1&&isUserHandle"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="onCancelPlayApply"
                >撤销申请</a>
                <a
                  v-if="platInterSts===1&&isUserHandle"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="onApplyPlayIntervene(2)"
                >补充凭证</a>
                <a
                  v-if="platInterSts===1&&isUserHandle"
                  href="JavaScript:void(0)"
                  class="action-a"
                  @click="onModifyReturnApply"
                >修改申请</a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 退款进度 -->
      <refundProgress :refund-detail="refundDetail" />

      <!-- 物流进度 -->
      <div
        v-if="deliveryDto && deliveryDto.traceFlag"
        class="return-progress"
      >
        <div v-if="deliveryDto.traceFlag">
          <div class="tit">
            {{ $t('orderDetails.logisticsStatus') }}
          </div>
          <!-- 申请关闭 -->
          <div
            v-for="(logItem,logIndex) in deliveryDto.traces"
            :key="logIndex"
            class="item"
          >
            <div class="time">
              {{ logItem.acceptTime }}
            </div>
            <div class="text-box">
              <div class="name acceptStation">
                {{ logItem.acceptStation }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改退款金额弹窗 -->
    <div
      v-if="isModifyRefundAmount"
      class="popup-mask"
    />
    <div
      v-if="isModifyRefundAmount"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('applyReturn.modifyRefundAmount') }}
        </div>
        <div
          class="close"
          @click="isModifyRefundAmount = false"
        />
      </div>
      <div class="con modify-amount">
        <div class="int-box">
          <input
            v-model="modifyAmount"
            type="text"
            class="int"
            :placeholder="$t('applyReturn.pleaseEnterAmount')"
            @blur="handleAmountInput"
            @focus="handleAmountInput"
          >
          <div
            v-if="!refundAmountError"
            class="max-amount"
          >
            {{ $t('applyReturn.maximumRefundable') }}￥{{ maxRefundAmount }}
          </div>
          <div
            v-if="refundAmountError"
            class="error"
          >
            {{ modifyAmount && Number.parseFloat(modifyAmount) > Number.parseFloat(maxRefundAmount)
              ? `${$t('applyReturn.maximumRefundable')}￥${maxRefundAmount}，${$t('applyReturn.reEnter')}`
              : $t('applyReturn.pleaseEnterAmount') }}
          </div>
        </div>
        <div class="foot-btn">
          <span
            class="confirm"
            @click="requestModify"
          >{{ $t('login.confirmChanges') }}</span>
        </div>
      </div>
    </div>
    <!-- / 修改退款金额弹窗 -->

    <!-- 物流信息弹框 -->
    <write-logistics-info
      v-if="showAdd"
      :refund-sn="refundSn"
      :order-number="refundDetail.orderNumber"
      :refund-delivery="refundDetail.refundDelivery"
      :return-money-sts="refundDetail.returnMoneySts"
      @toggle-addr-pop="refreshChange"
    />
    <!-- /物流信息弹框 -->
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import refundProgress from './components/refund-progress/index.vue'
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

onMounted(() => {
  document.title = $t('applyReturn.refundDetails')
  getRefundDetail() // 获取退款订单详情
})

onUnmounted(() => {
  intervenEndTimer && clearTimeout(intervenEndTimer)
  intervenFinishTimer && clearTimeout(intervenFinishTimer)
})

const refundSn = ref(route.query.refundSn) // 退款编号
// 退款项中是否使用了平台优惠 (使用了则不能修改退款金额)
const isUsedPlatformReduce = ref(false)
const maxRefundAmount = ref(0)
const refundDetail = ref({}) // 退款订单详情对象
const refundDelivery = ref({}) // 收货地址对象
const deliveryDto = ref({}) // 物流进度
const prodList = ref([]) // 赠品列表
const platInterSts = ref(0) // 平台介入状态
const canApplyPlatInter = ref(false) // 是否可申请平台介入
/**
 * 获取退款订单详情
 */
const getRefundDetail = () => {
  http.get('/p/orderRefund/info?refundSn=' + refundSn.value)
    .then(({ data }) => {
      let isUsedPlatformReducePar = false
      data.orderItems.forEach(orderItem => {
        if (orderItem.platformShareReduce && !isUsedPlatformReducePar) {
          isUsedPlatformReducePar = true
        }
      })
      platInterSts.value = data.platformInterventionStatus // 平台介入状态
      canApplyPlatInter.value = data.canApplyRefund // 是否可申请平台介入
      maxRefundAmount.value = data.maxRefundAmount
      isUsedPlatformReduce.value = isUsedPlatformReducePar
      refundDetail.value = data
      refundDelivery.value = data.refundDelivery
      deliveryDto.value = data.deliveryDto

      if (deliveryDto.value) {
        deliveryDto.traceFlag = !(!data.deliveryDto.traces || !data.deliveryDto.traces.length)
      } else {
        deliveryDto.value = {}
        deliveryDto.value.traceFlag = false
      }

      // 商品列表
      prodList.value = prodList.value.splice(0, prodList.value)
      const prods = data.orderItems
      prodList.value = prods
      if (prods && prods.length === 1 && prods[0].giveawayList && prods[0].giveawayList.length) {
        // 如果有赠品，单个商品时，将主商品和赠品放在同一级列表展示
        prodList.value = [...prods, ...prods[0].giveawayList]
      }
      if (data.platformInterventionStatus === 1) {
        const nowTime = new Date().getTime() // 当前时间
        if (data.interventionEndTime) {
          const endTime = new Date(data.interventionEndTime).getTime() // 添加凭证结束时间
          endTime - nowTime > 0 && intervenEndTimeCountdown()
          if (endTime - nowTime < 0 && data.platformProcessingEndTime) {
            const finishTime = new Date(data.platformProcessingEndTime).getTime() // 平台处理介入结束时间
            finishTime - nowTime > 0 && intervenFinishTimeCountdown()
          }
        }
      }
    })
}

const platInterHandleTips = computed(() => {
  if (isUserHandle.value) {
    return `等待平台客服处理，请在${refundDetail.value.interventionEndTime}前补充证，商家补充证可在售后进度中查看`
  } else if (isPlatHandle.value) {
    return `平台客服处理中，平台客服将在${refundDetail.value.platformProcessingEndTime}前处理`
  }
  return ''
})

// 添加凭证时间结束倒计时
let intervenEndTimer = null
const isUserHandle = ref(false) // 是否为用户处理介入中
const intervenEndTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(refundDetail.value.interventionEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    isUserHandle.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenEndTimer = setTimeout(intervenEndTimeCountdown, 1000)
  } else {
    isUserHandle.value = false
    intervenEndTimer && clearTimeout(intervenEndTimer)
    getRefundDetail() // 重新获取详情
  }
}

// 平台介入结束时间倒计时
let intervenFinishTimer = null
const isPlatHandle = ref(false) // 是否为平台处理介入中
const intervenFinishTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(refundDetail.value.platformProcessingEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    isPlatHandle.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenFinishTimer = setTimeout(intervenFinishTimeCountdown, 1000)
  } else {
    isPlatHandle.value = false
    intervenFinishTimer && clearTimeout(intervenFinishTimer)
    setTimeout(() => {
      getRefundDetail() // 重新获取详情
    }, 2000)
  }
}

/**
 * 撤销申请
 */
const cancelApply = () => {
  // 买家申请 || 卖家接受 || 卖家拒绝
  if (refundDetail.value.returnMoneySts === 1 || refundDetail.value.returnMoneySts === 7 || refundDetail.value.returnMoneySts === 2) {
    ElMessageBox.confirm($t('applyReturn.refundReason11'), $t('applyReturn.tips'), {
      confirmButtonText: $t('determine'),
      cancelButtonText: $t('cancel'),
      type: 'warning'
    }).then(() => {
      http.put('/p/orderRefund/cancel', refundSn.value)
        .then(() => {
          ElMessage({
            message: $t('applyReturn.refundReason12'),
            duration: 1000,
            type: 'success'
          })
          getRefundDetail()
        })
    }).catch(() => { })
  }
}

/**
 * 撤销平台介入申请
 */
const onCancelPlayApply = () => {
  ElMessageBox.confirm('是否确定撤销本次平台介入申请', $t('applyReturn.tips'), {
    confirmButtonText: $t('determine'),
    cancelButtonText: $t('cancel'),
    type: 'warning'
  }).then(() => {
    http.put('/p/orderRefund/cancel_platform_intervention', { refundSn: refundSn.value, refundId: refundDetail.value.refundId })
      .then(() => {
        ElMessage({
          message: $t('平台介入申请已撤销'),
          duration: 1000,
          type: 'success'
        })
        getRefundDetail()
      })
  }).catch(() => { })
}

// 申请平台介入or补充凭证
const onApplyPlayIntervene = (proofType) => {
  router.push({
    path: '/user-center/return-proof',
    query: { proofType, refundId: refundDetail.value.refundId, refundSn: refundDetail.value.refundSn }
  })
}

let orderInfo = {}
let unusedCount = 0
const onModifyReturnApply = () => {
  http.get('/p/myOrder/orderDetail', {
    params: {
      orderNumber: refundDetail.value.orderNumber
    }
  }).then(({ data }) => {
    orderInfo = data
    // 虚拟商品
    if (data.orderMold === 1) {
      // 计算待使用券码总数
      if (data.virtualInfoList?.length) {
        let unusedCountTemp = 0
        data.virtualInfoList.forEach(el => {
          if (el.isWriteOff === 0) {
            unusedCountTemp = unusedCountTemp + 1
          }
        })
        unusedCount = unusedCountTemp
      }
    }
    toApplyReturn()
  })
}

/**
 * 申请退款
 */
const toApplyReturn = () => {
  const platformFreeFreightAmount = orderInfo.platformFreeFreightAmount
  const transfee = platformFreeFreightAmount ? Number.parseFloat(new Big(platformFreeFreightAmount).minus(orderInfo.transfee || 0)).valueOf() : orderInfo.transfee
  const orderItemId = refundDetail.value.orderItems[0].orderItemId
  const refundType = refundDetail.value.refundType // refundType退款单类型（1:整单退款,2:单个物品退
  if (orderInfo.status === 2) { // 待发货
    const refundProdObj = {}
    if (refundType === 2) { // 单个退款
      applyLastProdRefund() // 是否最后一个订单项申请退款
      const orderItem = []
      orderInfo.orderItemDtos.forEach((el) => {
        el.isLastProd = isLastProd
        if (el.orderItemId === orderItemId) { // 如果当前的订单项id和点击传入的订单项id一致
          // 保存数据
          orderItem.push(el)
        }
      })
      refundProdObj.isOnlyProd = orderInfo.orderItemDtos.length === 1
      refundProdObj.refundType = refundType
      refundProdObj.orderItem = orderItem
      refundProdObj.buyerMobile = refundDetail.value.buyerMobile
    } else if (refundType === 1) { // 整单退款
      refundProdObj.orderItem = orderInfo.orderItemDtos
      refundProdObj.refundType = refundType
      refundProdObj.actualTotal = orderInfo.actualTotal
      refundProdObj.buyerMobile = refundDetail.value.buyerMobile
    }
    refundProdObj.orderId = orderInfo.orderId
    refundProdObj.refundId = refundDetail.value.refundId
    localStorage.setItem('bbcRefundProdObj', JSON.stringify(refundProdObj))
    router.push({
      path: '/user-center/apply-return',
      query: {
        orderNumber: refundDetail.value.orderNumber,
        transfee,
        status: orderInfo.status,
        refundType
      }
    })
  } else if (orderInfo.status !== 2) {
    const refundProdObj = {}
    if (refundType === 2) { // 单个退
      const orderItem = []
      orderInfo.orderItemDtos.forEach((el) => {
        if (el.orderItemId === orderItemId) { // 如果当前的订单项id和点击传入的订单项id一致
          // 保存数据
          orderItem.push(el)
        }
      })
      refundProdObj.orderItem = orderItem
      // 虚拟商品
      if (orderInfo.orderMold === 1) {
        // 1.无需核销：允许用户选择退款数量（writeOffNum 0无需核销 -1多次核销 1单次核销）
        refundProdObj.needWriteOffs = orderInfo.writeOffNum !== 0
        // 2.需要核销：展示最大可退款件数，不允许选择（最大可退款件数 = 待使用的核销券数）
        refundProdObj.maxRefundPieces = unusedCount
      }
      refundProdObj.buyerMobile = refundDetail.value.buyerMobile
    } else if (refundType === 1) { // 整单退款
      refundProdObj.orderItem = orderInfo.orderItemDtos
      refundProdObj.actualTotal = orderInfo.actualTotal
      refundProdObj.orderType = orderInfo.orderType
      refundProdObj.buyerMobile = refundDetail.value.buyerMobile
    }
    refundProdObj.orderId = orderInfo.orderId
    refundProdObj.refundId = refundDetail.value.refundId
    localStorage.setItem('bbcRefundProdObj', JSON.stringify(refundProdObj))
    router.push({
      path: '/user-center/apply-return',
      query: {
        orderNumber: refundDetail.value.orderNumber,
        status: orderInfo.status,
        transfee,
        isLastProd,
        orderItemId, // 订单项id
        refundType,
        orderMold: orderInfo.orderMold
      }
    })
  }
}

/**
 * 是否最后一个商品在执行单个商品退款事件
 */
const sum = ref([]) // 本单已申请单个退款的商品数组
let isLastProd = false // 最后一款商品
const applyLastProdRefund = () => {
  if (orderInfo.status === 2) { // 待发货状态下
    if (orderInfo.orderItemDtos.length > 1) { // 如果商品列表长度大于1
      const sumTemp = []
      // 遍历商品list
      orderInfo.orderItemDtos.forEach((el) => {
        if (el.refundSn) { // 如果拥有退款单号
          sumTemp.push(el)
          sum.value = sumTemp
        }
      })
      if (sum.value.length === orderInfo.orderItemDtos.length - 1) {
        // 如果拥有退款单号的商品数组长度等于商品列表数据长度-1，那么点击的这件商品就是最后一个订单项
        isLastProd = true
      }
    }
  }
}

const showAdd = ref(false) // 物流信息弹框显隐
/**
 * 填写 || 修改物流信息
 */
const writeLogisticsMsg = () => {
  showAdd.value = true
}

/**
* 刷新回调
*/
const refreshChange = (visible) => {
  showAdd.value = visible
}

/**
* 跳转到商品详情页
*/
const toProdDetails = (prodId, giveawayOrderItemId) => {
  if (!giveawayOrderItemId) {
    return
  }
  const newPage = router.resolve({ path: '/detail', query: { prodId } })
  let userId = null
  if (Cookie.get('bbcToken')) {
    userId = userStore.userId
  }
  http.get('/prod/prodInfo', {
    params: {
      prodId,
      userId
    }
  }).then(() => {
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  })
}

const isModifyRefundAmount = ref(false) // 修改金额弹窗
const modifyAmount = ref('') // 修改金额
const refundAmountError = ref(false)
/**
 * 修改退款金额
 */
const modifyRefundAmount = () => {
  modifyAmount.value = ''
  refundAmountError.value = false
  isModifyRefundAmount.value = true
}

const handleAmountInput = () => {
  refundAmountError.value = false
  if (!modifyAmount.value || !modifyAmount.value.trim()) {
    modifyAmount.value = modifyAmount.value.trim()
    return
  }
  modifyAmount.value = checkInput(modifyAmount.value)
}

const checkInput = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

const requestModify = () => {
  if (!modifyAmount.value || !modifyAmount.value.trim() || modifyAmount.value <= 0) {
    modifyAmount.value = modifyAmount.value.trim()
    refundAmountError.value = true
    return
  }
  if (Number.parseFloat(modifyAmount.value) > Number.parseFloat(maxRefundAmount.value)) {
    refundAmountError.value = true
    return
  }
  const param = {
    refundAmount: modifyAmount.value,
    refundSn: refundSn.value
  }
  http.put('/p/orderRefund/updateRefundAmount', param)
    .then(() => {
      ElMessage({
        message: '修改成功',
        type: 'success',
        duration: 1000
      })
      isModifyRefundAmount.value = false
      refundAmountError.value = false
      getRefundDetail()
    })
}

</script>
<style lang="scss" scoped>
@use "index";
</style>
